import React, { useState, useEffect } from 'react'
import { getCommodity, deleteCommodity, addCommodity, searchCommodity, updateCommodity } from '../../services/commodity'

import List from './List'
export default function () {

  const [commodityArr, setCommodityArr] = useState([]);
  const [pagination,setPagination] = useState({
    showSizeChanger:true,
    showQuickJumper:true,
    pageSizeOptions:[5,10,15,20,25],
    showTotal:total => `共 ${total} 条`
  })
  let [type,setType] = useState("");
  let [value,setValue] = useState("");

  const show = async (params={}) => {
    if(params.type){
      setType(params.type);
      setValue(params.value);
    }else{
      params.type = type;
      params.value = value;
    }
    let result = await getCommodity(params)
    setCommodityArr(result.rows)
    result.curPage = parseInt(result.curPage);
    setPagination({...pagination,...result});
  }

  useEffect(() => {
    show()
  }, [0])

  const toAdd = async (obj) => {
    await addCommodity(obj)
    show()
  }

  const toDelete = async (_id) => {
    await deleteCommodity(_id)
    show()
  }

  const toSearch = async (type, value) => {
    show({ type, value })
      // let result = await searchCommodity({ type, value })
      // setCommodityArr(result)
      // show()
  }

  const toUpdate = async (data) => {
    await updateCommodity(data)
    show()
  }

  return (
    <div >
        <List commodityArr={commodityArr} 
        toAdd={toAdd} toDelete={toDelete} 
        toUpdate={toUpdate} toSearch={toSearch}
        pagination={pagination}
        show={show}
        />
    </div>
  )

}
